import { createRouter, createWebHistory } from 'vue-router'
import { getCookie } from '@/utils/cookie'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginAndRegisterView.vue'),
    },
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/HomeView.vue'),
      redirect: '/main',
      children: [
        {
          path: '/main',
          name: 'MainView',
          component: () => import('@/views/MainView.vue'),
        },
        {
          path: '/products',
          name: 'ProductsView',
          component: () => import('@/views/ProductsView.vue'),
        },
        {
          path: '/dependencies',
          name: 'DependenciesView',
          component: () => import('@/views/DependenciesView.vue'),
        },
        {
          path: '/testReport',
          name: 'TestReportView',
          component: () => import('@/views/TestReportView.vue'),
        },
        {
          path: '/codeDiff',
          name: 'CodeDiffView',
          component: () => import('@/views/CodeDiffView.vue'),
        },
        {
          path: '/config',
          name: 'ConfigView',
          component: () => import('@/views/ConfigView.vue'),
        },
      ],
    },
  ],
})

// router/index.js
router.beforeEach((to, from, next) => {
  if (to.name !== 'login') {
    const userToken = getCookie('userToken')
    if (!userToken) {
      // cookie过期或不存在时，重定向到登录页
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
